
define([
  'require',
  'background',
  'player',
  'enemy',
  'collision', 
  'explosion'
], function(require, background, player, enemy, collision, explosion) {
  'use strict';
  
  var app, gameover = false;
  
  function init () {
    _initPIXI();
    background.init(app, app.stage);
    player.init(app, app.stage);
    enemy.init(app, app.stage);
    explosion.init(app, app.stage);

    // 启动更新线程
    app.ticker.add(function (delta) {
      if (gameover) return;
      background.update(delta);
      player.update(delta);
      enemy.update(delta);
    });

    // 启动碰撞检测线程
    app.ticker.add(function (delta) {
      if (gameover) return;

      enemy.data.enemyArr.forEach(function (e) {
        if (!e.visible) return;
        
        if (collision.rectDetect(e.getBounds(true), player.data.player.getBounds(true))) {
          // 玩家与敌机碰撞 gameover
          console.info('gameover!')
          onGameover();
        }

        player.data.bullet.data.bulletArr.forEach(function (bullet) {
          if (!bullet.visible) return;
          if (collision.rectDetect(bullet.getBounds(true), e.getBounds(true))) {
            // 敌机与自动碰撞，explode
            explosion.explode(e.position);
            player.data.bullet.recoverBullet(bullet);
            enemy.recoverEnemy(e);
            background.data.score.score();
          }
        });
      });
    });
  }

  function onGameover () {
    gameover = true;
  }

  function restart () {

  }

  function _initPIXI () {
    // 初始化一个app，并将view添加到body中
    app = new PIXI.Application({
      width: 300,
      height: 500,
      backgroundColor: 0x000000
    });
    document.body.appendChild(app.view);
    window.app = app;

    // 设置缩放模式
    // NEAREST 像素风格
    // LINEAR 模糊风格
    PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
  }

  return {
    init: init
  }


});





